<?php
namespace app\middleware;
use ReflectionClass;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class Auth implements MiddlewareInterface
{
    public function process(Request $request, callable $handler) : Response
    {
        //获取appid和秘钥
        $appid = $request->header('appid', '');
        if(!$appid){
            return json(['code' => 0, 'msg' => '缺失参数appid']);
        }
        $sign = $request->header('sign', '');
        if(!$sign){
            return json(['code' => 0, 'msg' => '缺失参数sign']);
        }
        $sign = base64_decode($sign);
        //密钥根据appid去找
        $method = 'DES-ECB';
        $passwd = '123123';//用户的密钥
        // $result = openssl_encrypt($opt, $method, $passwd,OPENSSL_RAW_DATA,'');
        // var_dump($result);
        $opt = openssl_decrypt($sign, $method, $passwd,OPENSSL_RAW_DATA);
        if(!$opt){
            return json(['code' => 403, 'msg' => '签名错误']);
        }
        parse_str($opt, $output);
        //$output 为请求加密参数 判断请求时间是否正确 前后差5秒
        if(!((time()-5)<$output['timestamp'] && $output['timestamp']< (time()+5))){
             return json(['code' => 402, 'msg' => '请求超时']);
        }

        // 通过反射获取控制器是哪个硬件
        $controller = new ReflectionClass($request->controller);
        //硬件id
        $hardware_id = $controller->getDefaultProperties()['hardware_id'] ?? '';
        if(!$hardware_id){
            return json(['code' => 401, 'msg' => '未找到硬件']);
        }
        //判断用户是否有此接口
        // 请求继续向洋葱芯穿越
        return $handler($request);
    }
    
}
